package com.chensf.studydemo.guide

import android.Manifest
import android.annotation.SuppressLint
import android.icu.util.IndianCalendar
import android.net.Uri
import android.os.Bundle
import android.provider.CalendarContract
import android.provider.ContactsContract
import android.text.format.Time
import android.util.Log
import androidx.activity.result.contract.ActivityResultContracts
import androidx.appcompat.app.AppCompatActivity
import com.android.calendarcommon2.EventRecurrence
import com.android.calendarcommon2.ICalendar
import com.chensf.studydemo.R
import com.google.ical.compat.jodatime.LocalDateIteratorFactory
import com.google.ical.values.RRule
import kotlinx.android.synthetic.main.activity_system_schedule.*
import java.lang.Exception
import java.text.SimpleDateFormat
import java.util.*

class SystemScheduleDemo : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_system_schedule)

        permissions.setOnClickListener {
            requirePermissions()
        }

        eventsBtn.setOnClickListener {
            getEvents()
        }
    }

    private fun requirePermissions() {
        val permissions =
            arrayOf(Manifest.permission.WRITE_CALENDAR, Manifest.permission.READ_CALENDAR)
        registerForActivityResult(ActivityResultContracts.RequestMultiplePermissions()) {

        }.launch(permissions)
    }

    val CALENDER_EVENT_URL = "content://com.android.calendar/events"
    val TAG = "foo"

    @SuppressLint("MissingPermission")
    fun getEvents() {
        val eventCursor =
            contentResolver.query(CalendarContract.Events.CONTENT_URI, null, null, null, null)
        val list = mutableListOf<Event>()
        while (eventCursor != null && eventCursor.moveToNext()) {
            val eventTitle =
                eventCursor.getString(eventCursor.getColumnIndex(CalendarContract.Events.TITLE))    //获取日历事件 的标题
            val description =
                eventCursor.getString(eventCursor.getColumnIndex(CalendarContract.Events.DESCRIPTION))  //获取日历事件 的描述
            val location =
                eventCursor.getString(eventCursor.getColumnIndex(CalendarContract.Events.EVENT_LOCATION)) //获取日历事件 的地点
            val calendarId =
                eventCursor.getLong(eventCursor.getColumnIndex(CalendarContract.Events.CALENDAR_ID))
            val startEventTime =
                eventCursor.getLong(eventCursor.getColumnIndex(CalendarContract.Events.DTSTART)) //获取 日程 开始的时间
            val endEventTime =
                eventCursor.getLong(eventCursor.getColumnIndex(CalendarContract.Events.DTEND))
            val allday =
                eventCursor.getInt(eventCursor.getColumnIndex(CalendarContract.Events.ALL_DAY))
            val duration =
                eventCursor.getString(eventCursor.getColumnIndex(CalendarContract.Events.DURATION))
            val rrule =
                eventCursor.getString(eventCursor.getColumnIndex(CalendarContract.Events.RRULE))
            val rdate =
                eventCursor.getString(eventCursor.getColumnIndex(CalendarContract.Events.RDATE))
            val exrule =
                eventCursor.getString(eventCursor.getColumnIndex(CalendarContract.Events.EXRULE))
            val exdate =
                eventCursor.getString(eventCursor.getColumnIndex(CalendarContract.Events.EXDATE))
            val original_id =
                eventCursor.getString(eventCursor.getColumnIndex(CalendarContract.Events.ORIGINAL_ID))
            val status =
                eventCursor.getInt(eventCursor.getColumnIndex(CalendarContract.Events.STATUS))
            val eventId =
                eventCursor.getLong(eventCursor.getColumnIndex(CalendarContract.Events._ID))
            list.add(Event(eventId,calendarId,eventTitle,description,location,startEventTime,endEventTime,allday,duration,rrule,rdate,status))
            rrule?.let {
                try {
                    val rRule = RRule("RRULE:$rrule")
                    val eventRecurrence = EventRecurrence()
                    val time = Time()
                    time.set(startEventTime)
                    eventRecurrence.setStartDate(time)
                    eventRecurrence.parse(rrule)
                    Log.e(TAG, "rRule=$rRule")
                }catch (e:Exception){
                    e.printStackTrace()
                }
            }
        }
        eventCursor?.close()
        Log.e(TAG, "list=${list}")
    }

    data class Event(
        val eventId: Long,
        val calendarId: Long,
        val eventTitle: String?,
        val description: String?,
        val location: String?,
        val startEventTime: Long,
        val endEventTime: Long,
        val allDay: Int,
        val duration: String?,
        val rrule: String?,
        val rdate: String?,
        val status: Int
    )

    private fun timeStamp2Date(toLong: Long): String {
        val format = SimpleDateFormat("yyyy-MM-dd HH:mm:ss")
        return format.format(toLong)
    }
}